import json
import os
from typing import Dict, Any
from pathlib import Path

class ConfigManager:
    """配置管理器 - 负责配置的持久化保存和加载"""
    
    def __init__(self):
        self.config_dir = Path("config")
        self.config_dir.mkdir(exist_ok=True)
        self.config_file = self.config_dir / "user_config.json"
    
    def save_config(self, config: Dict[str, Any]) -> bool:
        """保存配置到文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=2, ensure_ascii=False)
            print(f"[ConfigManager] 配置已保存到 {self.config_file}")
            return True
        except Exception as e:
            print(f"[ConfigManager] 保存配置失败: {str(e)}")
            return False
    
    def load_config(self) -> Dict[str, Any]:
        """从文件加载配置"""
        try:
            if self.config_file.exists():
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                print(f"[ConfigManager] 配置已从 {self.config_file} 加载")
                return config
            else:
                print(f"[ConfigManager] 配置文件不存在，使用默认配置")
                return self.get_default_config()
        except Exception as e:
            print(f"[ConfigManager] 加载配置失败: {str(e)}，使用默认配置")
            return self.get_default_config()
    
    def get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            # 清洗配置
            'clean_unicode': True,
            'remove_special_chars': True,
            'fix_line_breaks': True,
            'remove_headers_footers': False,
            'remove_duplicates': True,
            'remove_empty_lines': True,
            'min_line_length': 3,
            'preserve_formatting': False,
            
            # 切片配置
            'chunking_strategy': 'fixed_length',
            'chunking_config': {
                'strategy': '固定长度分段',
                'chunk_size': 1000,
                'overlap_size': 100,
                'respect_boundaries': True
            }
        }
    
    def update_config(self, updates: Dict[str, Any]) -> bool:
        """更新配置"""
        config = self.load_config()
        config.update(updates)
        return self.save_config(config)
    
    def reset_config(self) -> bool:
        """重置为默认配置"""
        return self.save_config(self.get_default_config())

# 全局配置管理器实例
config_manager = ConfigManager()